package tk.leafotto.sign2.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import tk.leafotto.sign2.R;
import tk.leafotto.sign2.dao.DbUtils;
import tk.leafotto.sign2.utils.ConstantValue;
import tk.leafotto.sign2.utils.DataUtil;
import tk.leafotto.sign2.utils.FileUtil;
import tk.leafotto.sign2.utils.SpUtil;

public class SetupActivity extends Activity {

    private EditText et_player;
    private String player;
    private long result = 0;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    if(result > 0){
                        Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_SHORT).show();
                        et_player.setText("");
                    }else if(result == -2) {
                        Toast.makeText(getApplicationContext(), "姓名重复", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(), "添加失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 1:
                    if(exportRS == 1){
                        Toast.makeText(getApplicationContext(), "备份顺利完成", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(), "备份失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 2:
                    Toast.makeText(getApplicationContext(), "数据还原完成", Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };
    private Button bt_import;
    private Button bt_export;
    private int exportRS;
    private String fileName;
    private TextView tv_ver;
    private TextView tv_update;
    private Switch sw_update;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_setup);
        initUI();
        initData();


    }

    private void initData() {
        //显示版本号
        PackageManager manager = this.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            tv_ver.setText("Ver " + info.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        Button bt_add = (Button) findViewById(R.id.bt_add);
        bt_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                player = et_player.getText().toString().trim();
                if(player.isEmpty()){
                    Toast.makeText(getApplicationContext(), "姓名不能为空", Toast.LENGTH_SHORT).show();
                }else {
                    new Thread(){
                        @Override
                        public void run() {
                            DbUtils dbUtils = DbUtils.instance(getApplicationContext());
                            result =dbUtils.addPlayer(player);
                            mHandler.sendEmptyMessage(0);
                        }
                    }.start();
                }
            }
        });

        bt_import.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isGrantExternalRW(SetupActivity.this)){
                    Intent intent = new Intent(getApplicationContext(), RestoreFilesActivity.class);
                    startActivityForResult(intent,1);
                }
            }
        });

        bt_export.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isGrantExternalRW(SetupActivity.this)){
                    AlertDialog.Builder builder = new AlertDialog.Builder(SetupActivity.this); //必须用this，不能用getApplicationContext
                    builder.setTitle("提醒");
                    builder.setMessage("学员及签到数据将备份到您的手机内存卡");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new Thread(){
                                @Override
                                public void run() {
                                    exportRS = new DataUtil().exportData(getApplicationContext());
                                    SystemClock.sleep(1000);
                                    mHandler.sendEmptyMessage(1);
                                }
                            }.start();
                            dialog.dismiss();
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                }
            }
        });

        sw_update.setChecked(checkUpdate());
        sw_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(checkUpdate()){
                    SpUtil.putBoolean(getApplicationContext(),ConstantValue.OPEN_UPDATE,false);
                }else {
                    SpUtil.putBoolean(getApplicationContext(),ConstantValue.OPEN_UPDATE,true);
                }
            }
        });
    }

    private boolean checkUpdate() {
        return SpUtil.getBoolean(this, ConstantValue.OPEN_UPDATE, false);
    }



    private void initUI() {
        et_player = (EditText) findViewById(R.id.et_player);
        bt_import = (Button) findViewById(R.id.bt_import);
        bt_export = (Button) findViewById(R.id.bt_export);
        tv_ver = (TextView) findViewById(R.id.tv_ver);
        tv_update = (TextView) findViewById(R.id.tv_update);
        sw_update = (Switch) findViewById(R.id.sw_update);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:
                if(data != null){
                    fileName = data.getStringExtra("fileName");
                    AlertDialog.Builder builder = new AlertDialog.Builder(SetupActivity.this); //必须用this，不能用getApplicationContext
                    builder.setTitle("警告");
                    builder.setMessage("即将从文件" + fileName + "恢复数据，现有数据将被清空，请确认是否继续？");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new Thread(){
                                @Override
                                public void run() {
                                    new DataUtil().importData(getApplicationContext(), fileName);
                                    SystemClock.sleep(1000);
                                    mHandler.sendEmptyMessage(2);
                                }
                            }.start();
                            dialog.dismiss();
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.show();

                }
                break;
        }
    }

    public static boolean isGrantExternalRW(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            activity.requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);
            return false;
        }
        return true;
    }
}
